#include <buola/gui.h>

#include <buola/algorithm/comparison.h>

#include <buola/widgets/coptionbox.h>
#include <buola/widgets/ctheme.h>

namespace buola { namespace gui {

std::vector<COptionBox*> COptionBox::mOptionBoxes;

COptionBox::COptionBox()
    :   mGroup(0)
{
    SetFocusMode(EFocusMode::TAB|EFocusMode::MOUSE);

    get_default_theme()->SetBackground(this);

    mOptionBoxes.push_back(this);

    mPressed=false;
}

COptionBox::~COptionBox()
{
    mOptionBoxes.erase(std::find(mOptionBoxes.begin(),mOptionBoxes.end(),this));
}

void COptionBox::GetPropertyNames(std::vector<std::string> &pNames)
{
    pNames.push_back("group");
    pNames.push_back("caption");

    CCheckWidget::GetPropertyNames(pNames);
}

void COptionBox::SetProperty(const std::string &p,const UAny &v)
{
    if(iequals(p,"group"))
    {
        SetGroup(v.Get<int>());
    }
    else if(equals(p,"caption"))
    {
        SetCaption(v.Get<std::wstring>());
    }
    else
    {
        CCheckWidget::SetProperty(p,v);
    }
}

void COptionBox::SetGroup(int pGroup)
{
    mGroup=pGroup;
}

void COptionBox::SetCaption(const std::wstring &pCaption)
{
    mCaption=pCaption;
    Refresh();
}

void COptionBox::NotifyChecked(COptionBox *pChecked)
{
    for(int i=0;i<mOptionBoxes.size();i++)
    {
        if(pChecked==mOptionBoxes[i]) continue;
        if(pChecked->Parent()!=mOptionBoxes[i]->Parent()) continue;
        if(pChecked->mGroup!=mOptionBoxes[i]->mGroup) continue;

        mOptionBoxes[i]->Check(false);
    }
}

///////////////////// Event handling //////////////////////

void COptionBox::OnExpose(const CExposeEvent &pE)
{
    get_default_theme()->DrawOptionBox(pE.mGC,this,CTheme::DRAW_NONE);
}

void COptionBox::OnButtonDown(const CMouseEvent &pE)
{
    if(pE.mButton!=EMouseButton::LEFT) return;
    if(GetStyle(STYLE_DISABLED)) return;
    mPressed=true;
}

void COptionBox::OnButtonUp(const CMouseEvent &pE)
{
    if(pE.mButton!=EMouseButton::LEFT) return;
    if(GetStyle(STYLE_DISABLED)) return;
    if(mPressed)
    {
        Check();
    }
    mPressed=false;
}

void COptionBox::OnFocusIn(const CFocusEvent &pE)
{
}

void COptionBox::OnFocusOut(const CFocusEvent &pE)
{
}

void COptionBox::OnChar(const CKeyEvent &pE)
{
}

void COptionBox::OnKeyDown(const CKeyEvent &pE)
{
}

void COptionBox::OnSize(const CGeometryEvent &pE)
{
}

void COptionBox::OnStyleChanged(TStyle pOld)
{
    if((pOld^GetStyle())&STYLE_FAKE)
    {
        if(GetStyle(STYLE_FAKE))
        {
            SetInputMode(EInputMode::MOUSETRANSPARENT);
        }
        else
        {
            SetInputMode(EInputMode::NORMAL);
        }
    }
}

void COptionBox::OnCWChecked()
{
    Refresh();
    if(IsChecked())
        NotifyChecked(this);
}

/*namespace gui*/ } /*namespace buola*/ }
